<template>
  <view class="phone-form">
    <sar-form ref="phoneFormRef" @submit="handleSubmit">
      <!-- 手机号输入框 -->
      <sar-form-item name="phone" :rules="rules.phone">
        <sar-input
          :model-value="form.phone"
          type="text"
          :maxlength="11"
          placeholder="请输入手机号"
          root-class="login-input"
          clearable
        >
          <template #prepend>
            <sar-icon class="ml-2" :name="IconPhone" size="36rpx" color="#3977FE" />
          </template>
        </sar-input>
      </sar-form-item>

      <!-- 验证码输入框 -->
      <sar-form-item name="code" :rules="rules.code">
        <sar-input
          :model-value="form.code"
          type="text"
          :maxlength="6"
          placeholder="请输入验证码"
          root-class="login-input"
          clearable
        >
          <template #prepend>
            <sar-icon class="ml-2" :name="IconCode" size="36rpx" color="#3977FE" />
          </template>
          <template #append>
            <view class="send-code-btn">
              <sar-button
                v-if="!isSending"
                size="small"
                :plain="true"
                root-class="code-btn"
                @click.stop="sendCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
              </sar-button>
              <sar-button
                v-else
                size="small"
                type="default"
                :plain="true"
                disabled
                root-class="code-btn"
              >
                发送中...
              </sar-button>
            </view>
          </template>
        </sar-input>
      </sar-form-item>

      <!-- 底部操作区域 -->
      <view class="flex items-center justify-end mt-[15rpx] mb-[25rpx]">
        <text class="text-[24rpx] text-[#3977FE]" @click="emit('forgotPassword')">忘记密码?</text>
      </view>

      <!-- 登录按钮 -->
      <sar-button
        form-type="submit"
        root-class="login-btn !w-full !rounded-[44rpx]"
        :loading="loading"
        :plain="false"
        block
      >
        登录
      </sar-button>
    </sar-form>

    <!-- 注册提示 -->
    <view class="register-tip mt-[15rpx] flex justify-center">
      <text class="text-[24rpx] text-[#666]">还没有账号？</text>
      <text class="text-[24rpx] text-[#3977FE] ml-[10rpx]" @click="emit('register')">立即注册</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import IconCode from '@/static/images/login/icon_code.svg'
import IconPhone from '@/static/images/login/icon_phone.svg'
import { type FormExpose, toast } from 'sard-uniapp'

const emit = defineEmits([
  'submit',
  'forgotPassword',
  'register',
])

const phoneFormRef = ref<FormExpose>()

const isSending = ref(false)
const countdown = ref(0)
let timer: number | null = null

const form = reactive({
  phone: '',
  code: '',
})
const loading = ref<boolean>(false)
// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
  ],
  code: [
    { required: true, message: '请输入验证码' },
    { len: 6, message: '验证码长度为6位' },
  ],
}

// 发送验证码
async function sendCode() {
  try {
    if (!form.phone) {
      toast('请先输入手机号', { position: 'center' })
      return
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(form.phone)) {
      toast('手机号格式不正确', { position: 'center' })
      return
    }

    // 如果正在倒计时，不允许重复发送
    if (countdown.value > 0) {
      return
    }

    isSending.value = true

    // 模拟发送验证码接口请求
    await new Promise<void>((resolve) => {
      setTimeout(() => {
        toast('验证码已发送', { position: 'center' })
        resolve()
      }, 1000)
    })

    // 开始倒计时
    countdown.value = 60

    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        if (timer) {
          clearInterval(timer)
          timer = null
        }
      }
    }, 1000)
  }
  catch {
    toast('验证码发送失败', { position: 'center' })
  }
  finally {
    isSending.value = false
  }
}

// 提交表单，处理手机号登录逻辑
async function handleSubmit() {
  try {
    if (!phoneFormRef.value) {
      toast('表单引用获取失败', { position: 'center' })
      return
    }

    // 表单验证
    await phoneFormRef.value.validate()

    // 获取登录参数
    const _loginParams = {
      phone: form.phone,
      code: form.code,
      type: 'phone',
    }

    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 登录成功，发送事件给父组件
    emit('submit', {
      success: true,
      userInfo: {
        phone: form.phone,
        // 其他用户信息...
      },
      type: 'phone',
    })
  }
  catch (error: any) {
    toast.fail(error?.message || '手机号登录失败')
    // 登录失败，发送事件给父组件
    emit('submit', {
      success: false,
      error: error?.message || '手机号登录失败',
      type: 'phone',
    })
  }
}

// 重置表单
function resetForm() {
  form.phone = ''
  form.code = ''
  if (phoneFormRef.value) {
    phoneFormRef.value.reset()
  }

  // 清除倒计时
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  countdown.value = 0
  isSending.value = false
}

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})

// 导出组件方法供父组件调用
defineExpose({
  resetForm,
})
</script>

<style lang="scss" scoped>
.phone-form {
  padding: 0 5rpx;
}

.send-code-btn {
  display: flex;
  align-items: center;
  height: 100%;
}

.code-btn {
  font-size: 22rpx !important;
  height: 50rpx !important;
  min-width: 130rpx;
  --sar-button-primary-color: #3977FE !important;
  --sar-button-primary-border-color: #3977FE !important;
}

.login-input {
  --sar-input-padding-x: 0;
  --sar-input-height: 76rpx;
  --sar-input-line-height: 1.2;
  margin-bottom: 15rpx;
}

.login-btn {
  --sar-button-height: 80rpx;
  --sar-button-primary-color: #FFFFFF !important;
  --sar-button-primary-background-color: #3977FE !important;
  --sar-button-primary-border-color: #3977FE !important;
  --sar-button-primary-active-background-color: #3369E8 !important;
  --sar-button-primary-active-border-color: #3369E8 !important;
}

.register-tip {
  margin-top: 15rpx;
}

.flex.items-center.justify-end {
  margin-top: 15rpx;
  margin-bottom: 25rpx;
}
</style>
